module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", count = 0, currentName = "", handler;
    function isGroup() {
        let el = document.querySelector('section svg>foreignObject>div>img.circularImage__1ce5d');
        if (el) return true;
        let url = window.location.href;
        return url.includes("channels/") && !url.includes("@me");
    }
    async function getChatId(times = 0) {
        let url = window.location.href;
        let id = '';
        if (url.includes("@me")) {
            id = url?.split('@me/')[1];
        } else if (url.includes("channels/")) {
            id = url?.split('channels/')[1];
        }
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    return {
        config: {
            friendList: '#app-mount div.sidebarList_c48ade>nav',
            chat: '#app-mount div.chat_f75fb0',
            input: 'main>form.form_f75fb0 div[role="textbox"][contenteditable]',
            msgBox: 'main ol[role="list"][data-list-id="chat-messages"]',
            inMsg: "",
            outMsg: "",
            setting: "main>form.form_f75fb0 div.slateContainer_ec4baf",
            tips: {
                in: '#app-mount div.subtitleContainer_f75fb0>section div.titleWrapper__9293f',
                out: 'main>form.form_f75fb0'
            },
            crm: {
                // listener: '#LeftColumn-main',
                top: '#app-mount div.subtitleContainer_f75fb0>section div.titleWrapper__9293f>h1',
                left: ""
            },
            placeholder: {
                selector: "main>form.form_f75fb0 div.textArea__74017 div.placeholder__1b31f"
            },
            extra: {//其他会触发对话框变动的情况处理
                selector: 'nav>ul div.listItem__650eb',
                level: 20,
                delay: 600,
            },
            autoCount: 20,
        },
        init(_handler) {
            handler = _handler;
            let nameEl = document.querySelector('section.panels_c48ade div[data-text-variant="text-sm/medium"]');
            currentName = nameEl?.textContent || "";
        },
        getUnread() {
            count = 0;
            const els = document.querySelector('.lowerBadge_cc5dd2 .numberBadge__2b1f5');
            try {
                count = EdtApi.safeParseInt(els.textContent);
            } catch (error) {
            }
            return count;
        },
        getChatInfo() {
            return new Promise(async (resolve) => {
                chatId = await getChatId();
                // console.log("chatId:", chatId, isGroup());
                resolve({ id: chatId, isGroup: isGroup() });
            });
        },
        getChatTitle(chatEl = document) {
            let titleEl = chatEl.querySelector('#app-mount div.subtitleContainer_f75fb0>section div.titleWrapper__9293f>h1');
            return titleEl?.textContent || "";
        },
        handlerEnter(event) {
            if (!event.isTrusted) return;
            if (EdtApi.closest(event.target, 'div.search__49676,div.search__1ac1c', 20)) {//回车搜索
                if ("function" == typeof handler.doEnter) handler.doEnter(event.target);
                return;
            }
        },
        getMessageList() {
            let messages = {};
            let lis = document.querySelectorAll('main ol[role="list"][data-list-id="chat-messages"]>li'), titleEl, item, litems = [], ritems = [];
            lis?.forEach(li => {
                titleEl = li.querySelector('h3 span.username_c19a55');
                item = li.querySelector('div.messageContent_c19a55');
                if (item) {
                    if (titleEl?.textContent == currentName) {
                        ritems.push(item);
                    } else {
                        litems.push(item);
                    }
                }
            });
            messages.in = litems;
            messages.out = ritems;
            // console.log("getMessageList:::", messages);
            return messages;
        },
        getText(msgBox) {
            return msgBox?.textContent || "";
        },
        getIptMsg(inputEl) {
            if (!inputEl) return '';
            try {
                let texts = [], items = inputEl.querySelectorAll('div[data-slate-node="element"]');
                items?.forEach((item) => {
                    texts.push(item.textContent || "");
                });
                return texts.join("\n");
            } catch (error) {
                console.error(error);
            }
            return "";
        },
        getUserInfo() {
            try {
                let userEl = document.querySelector('section.panels_c48ade');
                let phoneEl = userEl.querySelector('div[data-text-variant="text-xs/normal"] div.hovered__0263c');
                let nameEl = userEl?.querySelector('div[data-text-variant="text-sm/medium"]');
                let account = phoneEl?.textContent || "";
                let userName = nameEl?.textContent || "";
                let avatarEl = userEl?.querySelector("svg img.avatar__44b0c");
                let avatar = avatarEl?.getAttribute("src") || "";
                if (!currentName) currentName = userName;
                if (avatar) avatar = `https://discord.com${avatar}`;
                return {
                    avatar,
                    userName,
                    account,
                    toDataUrl: true
                };
            } catch (error) {
                return null;
            }
        }
    }
};